<template>
    <div class="white-box">
        <detail-item title="供应商名称" bottom="24px" :value="infos.title" />
        <detail-item title="授权类型" bottom="24px">
            <el-radio-group v-model="radio_class" @change="changeRadio">
                <el-radio :label="item.label" v-for="item in radio_label" :key="item.label">
                    {{ item.title }}
                </el-radio>
            </el-radio-group>
        </detail-item>

        <div class="slg-table">
            <div class="task-one">
                <div class="task-one__item">
                    <span class="task-one__label">授权名称：</span>
                    <el-input placeholder="输入授权名称搜索" v-model.trim="search_text" clearable></el-input>
                </div>
                <div class="task-one__btn clearfix">
                    <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
                </div>
            </div>
            <div class="table-mb">
                <el-button type="default" plain @click="allDel">批量删除</el-button>
                <el-button type="primary" @click="clickAdd">添加</el-button>
            </div>
            <el-table
                class="table-mb"
                v-loading="loading"
                :data="arr_data"
                @selection-change="handleAllSelected"
                :header-cell-style="{ background: '#F5F7FA' }"
                element-loading-background="rgba(255, 255, 255, 0.6)"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="auth_id" label="授权ID" width="100"></el-table-column>
                <el-table-column prop="auth_name" label="授权名称" min-width="260"></el-table-column>
                <el-table-column prop="auth_level" label="授权等级" min-width="220"></el-table-column>
                <el-table-column label="供应商" min-width="300">
                    <template #default="{ row }">
                        <p>{{ row.supplier_name }}[ID: {{ row.supplier_id }}]</p>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" class-name="operation-nav" fixed="right">
                    <template #default="{ row }">
                        <el-button class="theme-btn" link type="primary" @click="clickEdit(row)">编辑 </el-button>
                        <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                            <template #reference>
                                <el-button class="theme-btn" link type="primary">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                background
                v-model:current-page="page"
                v-model:page-size="pageSize"
                :page-sizes="pageSizeNum"
                :total="totalNums"
                layout="total, sizes, prev, pager, next, jumper"
            >
            </el-pagination>

            <!-- 添加/编辑 -->
            <el-dialog
                v-model="dialogUpdate"
                :title="classType == 1 ? '添加授权' : '编辑授权'"
                width="580px"
                :append-to-body="true"
                :destroy-on-close="true"
                :close-on-click-modal="false"
                @close="closeUpdate"
            >
                <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="120px">
                    <el-form-item label="选择授权" prop="grants" v-if="classType == 1">
                        <el-input
                            v-model.trim="ruleForm.grants"
                            readonly
                            :suffix-icon="ArrowRight"
                            placeholder="请选择授权的商品/分类"
                            clearable
                            @click="clickGrant"
                        >
                        </el-input>
                    </el-form-item>
                    <el-form-item label="授权等级" prop="labels">
                        <el-checkbox-group v-model="ruleForm.labels" :key="checkbox_key">
                            <el-checkbox :label="item.level_id" :checked="item.selected == 1" v-for="item in labelArrs" :key="item.level_id">
                                {{ item.level_name }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item>
                        <div class="flexs" style="margin-top: 30px">
                            <el-button type="primary" :loading="form_loading" @click="submitForm(ruleRef)">
                                {{ classType == 1 ? "确认添加" : "确认修改" }}
                            </el-button>
                            <el-button @click="resetForm(ruleRef)">重置</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-dialog>

            <!-- 选择商品或分类 -->
            <el-dialog
                v-model="dialogGrant"
                :title="radio_class == 0 ? '选择分类' : '选择商品'"
                width="800px"
                top="10vh"
                :append-to-body="true"
                :destroy-on-close="true"
                draggable
                @close="closeGrant"
            >
                <div class="task-one" style="margin-top: 0">
                    <div class="task-one__item">
                        <el-input placeholder="请输入名称关键词" v-model="grant_name" @keyup.enter.native="grantSearch" clearable></el-input>
                    </div>
                    <div class="task-one__item">
                        <el-button type="primary" :loading="grant_btn" :icon="Search" @click="grantSearch">搜索</el-button>
                    </div>
                </div>
                <el-table
                    class="table-mb"
                    :data="grant_arrs"
                    :header-cell-style="{ background: '#F5F7FA' }"
                    element-loading-background="rgba(255, 255, 255, 0.6)"
                    v-loading="grant_loading"
                >
                    <el-table-column prop="auth_id" :label="radio_class == 0 ? '分类ID' : '商品ID'" width="120"></el-table-column>
                    <el-table-column prop="auth_name" :label="radio_class == 0 ? '分类名称' : '商品名称'"></el-table-column>
                    <el-table-column label="操作" width="100">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click.stop="confirmGrant(row)"> 选择 </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination background v-model:current-page="grant_page" :page-size="10" :total="totalGrant" layout="total, prev, pager, next, jumper">
                </el-pagination>
            </el-dialog>
        </div>
    </div>

    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive, onBeforeUnmount } from "vue"
import { useRoute } from "vue-router"
import { Search, ArrowRight } from "@element-plus/icons-vue"
import OneLoad from "@mixins/one-load"
import DetailItem from "@components/DetailItem.vue"
import GoBack from "@components/GoBack.vue"

const route = useRoute()
const { proxy } = getCurrentInstance()

const sid = route.query.id // 供应商ID
onMounted(() => {
    sid && getInfo()
    getLevel()
})

onBeforeUnmount(() => {})

// 获取信息
const infos = ref({})
function getInfo() {
    proxy.$axios
        .get("supplier/auth/info", {
            params: {
                supplier_id: sid,
            },
        })
        .then((res) => {
            getList()
            if (res.data.code == 0) {
                let result = res.data.data
                infos.value = result
                radio_class.value = result.auth_type
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, search_text, search_btn, pubParams, pubRefreshParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})
function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        supplier_id: sid,
        so: search_text.value,
    }
    getdata("supplier/auth/index", params)
}
// 搜索
const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

/**
 * 添加/编辑
 * @param {Boolean} dialogUpdate 添加/编辑弹窗状态
 * @param {Boolean} form_loading 提交按钮状态
 * @param {Number} classType 弹窗类型，1是添加，2是编辑
 * @param {Number} checkbox_key 选择框的key值
 * @param {Array} ruleRef 表单规则
 * @param {Object} ruleForm  表单字段
 * @param {Object} ruleCheck  表单提示
 */
const form_loading = ref(false)
const dialogUpdate = ref(false)
const classType = ref(1)
const checkbox_key = ref(0)
const ruleRef = ref(null)
const ruleForm = reactive({
    id: "", // 自增授权ID
    grants: "",
    grants_id: "", // 授权ID
    labels: [],
})
const ruleCheck = reactive({
    // labels: [{ type: 'array', required: true, message: "请勾选授权等级", trigger: "change" }],
})
const submitForm = (formEl) => {
    // 确认
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (ruleForm.grants == "" && classType.value == 1) {
                proxy.$message({ message: "请选择授权的商品/分类", type: "warning" })
                return
            }
            if (ruleForm.labels.length == 0) {
                proxy.$message({ message: "请勾选授权等级", type: "warning" })
                return
            }

            form_loading.value = true
            let data = {
                auth_level: ruleForm.labels,
            }
            if (classType.value == 1) {
                data.supplier_id = sid
                data.auth_id = ruleForm.grants_id
            } else {
                data.id = ruleForm.id
            }
            let url = classType.value == 1 ? "supplier/auth/add" : "supplier/auth/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogUpdate.value = false
                        proxy.$message({ message: `${classType.value == 1 ? "添加成功！" : "编辑成功！"}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const clickAdd = () => {
    // 点击添加
    dialogUpdate.value = true
    classType.value = 1
}
const clickEdit = (row) => {
    // 点击编辑
    dialogUpdate.value = true
    getEditLevel(row.id)
    setTimeout(() => {
        classType.value = 2
        ruleForm.id = row.id
    }, 50)
}
function getEditLevel(id) {
    // 获取编辑时等级
    proxy.$axios
        .get("supplier/auth/update", {
            params: {
                id,
            },
        })
        .then((res) => {
            checkbox_key.value += 1 // 通过key值不同，触发组件刷新
            if (res.data.code == 0) {
                labelArrs.value = res.data.data
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
const closeUpdate = () => {
    dialogUpdate.value = false
    resetForm(ruleRef.value)
}

/**
 * 获取商品等级
 * @param {Array} labelArrs 等级数组
 * @param {Function} getLevel 获取等级-用于添加授权
 */
const labelArrs = ref([])
function getLevel() {
    proxy.$axios
        .get("supplier/auth/add")
        .then((res) => {
            if (res.data.code == 0) {
                labelArrs.value = res.data.data
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 选择授权商品/分类
 * @param {Boolean} dialogGrant 弹窗状态
 * @param {Boolean} grant_loading 加载状态
 * @param {Number} grant_page 页码
 * @param {Number} totalGrant 总数
 * @param {Array} grant_arrs 商品/分类数组
 * @param {Function} getSslectGrant 获取商品/分类数组
 */
const dialogGrant = ref(false)
const grant_loading = ref(true)
const grant_page = ref(1)
const totalGrant = ref(0)
const grant_arrs = ref([])
const clickGrant = () => {
    dialogGrant.value = true
    getSslectGrant()
}
const confirmGrant = (row) => {
    ruleForm.grants = row.auth_name
    ruleForm.grants_id = row.auth_id
    dialogGrant.value = false
}
watch(grant_page, (val) => {
    grant_arrs.value = []
    getSslectGrant()
})
function getSslectGrant() {
    grant_loading.value = true
    proxy.$axios
        .get("supplier/auth/authSelect", {
            params: {
                page: grant_page.value,
                limit: 10,
                supplier_id: sid,
                so: grant_name.value,
            },
        })
        .then((res) => {
            grant_loading.value = false
            grant_btn.value = false
            if (res.data.code == 0) {
                let result = res.data
                totalGrant.value = result.count
                grant_arrs.value = result.data
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {
            grant_btn.value = false
            grant_loading.value = false
        })
}
const closeGrant = () => {
    dialogGrant.value = false
    grant_name.value = ""
}

/**
 * 搜索选择授权商品/分类
 * @param {String} grant_name 搜索字段
 * @param {Boolean} grant_btn 搜索状态
 */
const grant_name = ref("")
const grant_btn = ref(false)
const grantSearch = () => {
    grant_btn.value = true
    grant_page.value = 1
    totalGrant.value = 0
    grant_arrs.value = []
    getSslectGrant()
}

// 删除单个
const clickDel = (row) => {
    postDel(row.id)
}
// 删除多个
const ids = ref([])
const handleAllSelected = (val) => {
    let arrs = []
    for (let i = 0; i < val.length; i++) {
        arrs.push(val[i].id)
    }
    ids.value = arrs
}
const allDel = () => {
    if (ids.value.length == 0) {
        proxy.$message({ message: "请选择需要删除的数据", type: "warning" })
        return
    }
    postDel(ids.value)
}
// 删除接口
function postDel(params) {
    proxy.$axios
        .post("supplier/auth/delete", {
            id: params,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 授权类型
 * @param {Number} radio_class radio选中值
 * @param {Array} radio_label radio数组
 * @param {Function} changeRadio radio切换事件
 */
const radio_class = ref(0)
const radio_label = ref([
    {
        label: 0,
        title: "分类授权",
    },
    {
        label: 1,
        title: "商品授权",
    },
])
const changeRadio = (val) => {
    proxy.$axios
        .post("supplier/auth/set", {
            supplier_id: sid,
            auth_type: val,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubRefreshParams(getList)
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "SupplierListGrant",
}
</script>

<style lang="less" scoped>
:deep(.el-checkbox__inner) {
    width: 18px;
    height: 18px;

    &::after {
        width: 4px;
        height: 9px;
        left: 6px;
        top: 1px;
    }
}

.slg-table {
    border-top: @border-gray;
    padding-top: @padding-xl;
}

:deep(.el-radio) {
    height: auto;
}
</style>
